﻿using System;
using System.Xml.Linq;
using RssNewsFeeder.Model.Data;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RssNewsFeeder.ErrorHandler;

namespace RssNewsFeeder.Model.Business
{
    public class NewsItemCollection: IDisposable
    {
        private DataAccessLayer _dal = DataAccessLayer.CreateInstance();
        private List<NewsItem> _newsItemCollection;

        public NewsItemCollection() 
        {
            _newsItemCollection = new List<NewsItem>();
        }

        public string NewsType { get; set; }
        public string NewsCompany { get; set; }
        public int ItemSize { get; set; }

        public List<NewsItem> NewsItems
        {
            get { return GetNewsItemCollection();}
        }
        private List<NewsItem> GetNewsItemCollection()
        {
            try
            {
                // Get feed URL from xml files
                string feedUrl = _dal.GetFeedURL(NewsCompany, NewsType);
                
                System.IO.Stream xmlFeed = _dal.GetXMLFeed(feedUrl);
                
                // Get NewsItems from rss feed
                XDocument dbRSS = XDocument.Load(xmlFeed);
                var RssFeed = from item in dbRSS.Descendants("item")
                              select item;
                foreach (var n in RssFeed)
                {

                    NewsItem news = new NewsItem()
                    {
                        NewsType = this.NewsType,
                        Newscompany = this.NewsCompany,
                        NewsBody = n.Element("description").Value,
                        NewsHeader = n.Element("title").Value,
                        PubDate = n.Element("pubDate").Value,
                        URL = n.Element("link").Value
                    };
                    _newsItemCollection.Add(news);
                }
                return _newsItemCollection;
            }
            catch (Exception ex)
            {
                Error.LogError(ex.Message.ToString());
                return null;
            }

        }

        #region IDisposable Members

        void IDisposable.Dispose()
        {
            _newsItemCollection.Clear();
        }

        #endregion
    }
}
